import pickle
import pandas as pd
from pandas import DataFrame


class ObjMemory (): #处理对象读取和存储

    def LoadObj (self,path): #载入对象
        Obj = None

        with open (path,'rb+') as ObjFile:
            Obj = pickle.load(ObjFile)

        return Obj

    
    def SaveObj (self,Obj,path): #保存对象
        with open (path,'wb+') as ObjFile:
            pickle.dump(Obj,ObjFile)
            

class UnTaggedText (): #UTagged_Text
    OM = ObjMemory()

    def __init__(self) -> None:
        self.Base = None
        self.Data = None
        self.word_list = []
        self.mat = [] #mat[i][j]=1说明第i个词语是第j个词语的子串
        self.col = 0
        self.datasize = 0
        self.next_id = 0

        self.Base = self.OM.LoadObj('./System/TrainText.pkl')
        self.Data = self.Base.Data
        self.Data['Sample_id'] = 0
        self.Data['Text'] = ''
        self.Data = self.Data.iloc[0:0,:]
        self.word_list = self.Base.word_list
        self.mat = self.Base.mat
        self.col = self.Data.shape[1]
        self.datasize = 0


    def Update (self): #更新数据列
        self.Base = self.OM.LoadObj('./Local/TrainText_Buffer.pkl')
        self.word_list = self.Base.word_list
        self.mat = self.Base.mat

        former = self.Data.iloc[:,0:self.col-2]
        latter = self.Data.iloc[:,self.col-2:self.col]

        for i in range (self.col-2,self.Base.col):
            former[self.Base.Data.iloc[:,i].name] = 0
        
        self.Data = pd.concat([former,latter],axis=1)

        self.col = self.Data.shape[1]


    def AddSample (self,sample):
        self.Data = pd.concat([self.Data,sample])
        self.datasize += 1
        self.next_id += 1